﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Spore.Utils
{
   public class ThreadWorkExecuter
    {
      private ThreadExeResult resultDes;
      private const string workIsNull = "工作项为空";
      public ThreadWorkItem WorkItem
      {
          get;
          private set;
      }
      public ThreadWorkExecuter(ThreadWorkItem workItem)
      {
          this.WorkItem = workItem;
          workItem.ExeState = ThreadWorkItemState.WaitExe;
      }
      internal void ExeDele()
      {
          if(this.WorkItem.IsCancel) return;
          this.WorkItem.ExeState = ThreadWorkItemState.Exeing;
          if (WorkItem == null)
          {
              resultDes = new ThreadExeResult();
              resultDes.IsSucced = false;
              resultDes.ExeDes = workIsNull;
              this.OnEndExe();
          }
          try
          {
              if (!this.WorkItem.IsCancel)
              {
                 object obj=  this.WorkItem.WorkDele.DynamicInvoke(WorkItem.WorkParams);
                 resultDes = new ThreadExeResult();
                 resultDes.IsSucced = true;
                 resultDes.Result = obj;
                 resultDes.ExeDes= "执行成功";
                 this.OnEndExe();
              }
          }
          catch(Exception ex)
          {
              resultDes = new ThreadExeResult();
              resultDes.IsSucced = false;
              resultDes.ExeDes = ex.Message;
              this.OnEndExe();
          }
      }
      private void OnEndExe()
      {
          this.WorkItem.ExeResult = resultDes;
          this.WorkItem.ExeState = ThreadWorkItemState.EndExe;
      }
    }
}
